const { Article, User } = require('../model')

exports.getArticles = async (req, res, next) => {
    try {
        const { limit = 20, offset = 0, tag, author } = req.query
        const filter = {}
        if (tag) {
            filter.tagList = tag
        }

        if (author) {
            const user = await User.findOne({ username: author })
            filter.author = user ? user._id : null
        }


        const articles = await Article.find(filter)
            .skip(Number.parseInt(offset)) //跳过多少条
            .limit(Number.parseInt(limit))  //取多少条
            .sort({
                // 以创建时间倒序  -1: 倒序  1: 顺序
                createdAt:-1
            })
        const articlesCount = await Article.countDocuments()
        res.status(200).json({
            articles,
            articlesCount
        })
    } catch (error) {
        next(error)
    }
}
exports.getFeedArticles = async (req, res, next) => {
    try {
        res.send('getFeedArticles')
    } catch (error) {
        next(error)
    }
}

exports.getArticle = async (req, res, next) => {
    try {
        const article = await Article.findById(req.params.articleId)
        // populate('author')
        if (!article) {
            return res.status(404).end()
        }
        res.status(200).json({
            article
        })

    } catch (error) {
        next()
    }
}

//更新文章
exports.updateArticle = async (req, res, next) => {
    try {
        const article = req.article
        const bodyArticle = req.body.article
        article.title = bodyArticle.title||article.title
        article.description = bodyArticle.description||article.description
        article.body = bodyArticle.body||article.body
        await article.save()
        res.status(201).json({
            article
        })
    } catch (error) {
        next()
    }
}

exports.createArticle = async (req, res, next) => {
    try {
        const article = new Article(req.body.article)
        // 通过token 得到user._id,从而得到作者信息
        article.author = req.user._id

        // 这里会报错,没找到原因
        // article.populate('author').execPopulate()

        await article.save()
        res.status(201).json({
            article
        })
    } catch (error) {
        next(error)
    }
}
exports.deleteArticle = async (req, res, next) => {
    try {
        const article = req.article
        await article.remove()
        res.status(204).end()
    } catch (error) {
        next(error)
    }
}
// 添加文章评论
exports.createArticleComment = async (req, res, next) => {
    try {
        res.send('createArticleComment')
    } catch (error) {
        next(error)
    }
}
exports.getArticleComments = async (req, res, next) => {
    try {
        res.send('getArticleComments')
    } catch (error) {
        next(error)
    }
}
exports.deleteArticleComments = async (req, res, next) => {
    try {
        res.send('deleteArticleComments')
    } catch (error) {
        next(error)
    }
}
